package com.chance.cc.crawler.development.scripts.yyjjb;

import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.development.scripts.dayao.DayaoCrawlerScript;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.article;
import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.interaction;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;

/**
 * created by ljl 20210628
 * 医药经济报  大健康板块
 */
public class YyjjbHealthCrawlerScript extends CrawlerCommonScript {

    private Logger log = LoggerFactory.getLogger(YyjjbHealthCrawlerScript.class);

    public static final String listUrlPrefix = "http://www.yyjjb.com.cn/news/list/25";

    /**
     * 脚本domain定义
     *
     * @return
     */
    public String domain() {
        return "yyjjbHealth";
    }

    /**
     * 进入脚本的正则列表
     */
    public void initUrlRegulars() {
        addUrlRegular("http://www.yyjjb.com.cn/news/list/25\\S*"); //翻页
        addUrlRegular("http://www\\.yyjjb\\.com\\.cn/\\d{2}/\\d{2}/\\d+_\\d+\\.shtml"); //详情
    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }

    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<>();

        //下一页解析
        String url = httpPage.getRequest().getUrl();
        int pageNum = 2;
        if(url.contains("page")){
            pageNum = Integer.parseInt(url.split("=")[1]) + 1;
        }
        String nextPageUrl = listUrlPrefix + "?page=" + pageNum;
        CrawlerRequestRecord turnPageRequest = CrawlerRequestRecord.builder()
                .turnPageRequest(crawlerRequestRecord)
                .recordKey(nextPageUrl)
                .httpUrl(nextPageUrl)
                .releaseTime(System.currentTimeMillis())
                .build();
        parsedLinks.add(turnPageRequest);

        //明细页解析
        List<Selectable> nodes = httpPage.getHtml().xpath("//li[@class=\"news-item\"]").nodes();
        for (Selectable node : nodes) {
            String itemUrl = "http://www.yyjjb.com.cn" + node.xpath(".//a/@href").get();
            if (StringUtils.isBlank(itemUrl)) {
                continue;
            }

            String pubTime = node.xpath("./p/a/span[1]/text()").get();
            pubTime = pubTime.substring(5);

            try {
                long releaseTime = DateUtils.parseDate(pubTime, "yyyy-MM-dd").getTime();
                CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .recordKey(itemUrl)
                        .httpUrl(itemUrl)
                        .releaseTime(releaseTime)
                        .resultLabelTag(article)
                        .build();
                parsedLinks.add(itemRecord);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

        return parsedLinks;
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {

        List<CrawlerData> crawlerDataList = new ArrayList<>();
        if (crawlerRecord.tagsCreator().resultTags().hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));

        }

        if (crawlerRecord.tagsCreator().resultTags().hasDataType(interaction)) {
            crawlerDataList.add(washInteraction(crawlerRecord, page));
        }

        return crawlerDataList;
    }

    public CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        try {
            List<String> texts = httpPage.getHtml().xpath("//div[@class=\"detail-article\"]/p/text()").all();
            List<String> allImages = httpPage.getHtml().xpath("//div[@class=\"detail-article\"]/p/img/@src").all();
            if(texts.get(0).startsWith("此内容为《医药经济报》融媒体平台原创")){
                texts = httpPage.getHtml().xpath("//div[@class=\"detail-article\"]/p/span/text()").all();
                allImages = httpPage.getHtml().xpath("//div[@class=\"detail-article\"]/p/span/img/@src").all();
            }
            StringBuffer conents = new StringBuffer();
            for (String text : texts) {
                conents.append(text).append(" ");
            }
            String content = unescapeHtml2J(conents.toString().trim());

            StringBuffer sbImage = new StringBuffer();
            for (String allImage : allImages) {
                sbImage.append(allImage).append("\\x01");
            }

            String releaseTimeStr = httpPage.getHtml().xpath("//div[@class=\"detail-title\"]/p/span[1]").get();

            String itemUrl = httpPage.getRequest().getUrl();
            String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1).split("\\.")[0];

            String title = StringEscapeUtils.unescapeHtml(httpPage.getHtml().xpath("//div[@class=\"detail-title\"]/h2").get());

            String author = httpPage.getHtml().xpath("(//div[@class=\"detail-title\"]/p/span)[2]").get();
            if(author.startsWith("作者")){
                author = author.substring(3);
            }else{
                author = "";
            }

            CrawlerData crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .url(itemUrl)
                    .releaseTime(DateUtils.parseDate(releaseTimeStr, "发布时间：yyyy-MM-dd HH:mm:ss").getTime())
                    .addContentKV(Field_Content, content)
                    .addContentKV(Field_Title, title)
                    .addContentKV(Field_Author, author)
                    .addContentKV(Field_Images,sbImage.toString())
                    .build();
            return crawlerData;
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    public CrawlerData washInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        return null;
    }

    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {
    }

    public static String unescapeHtml2J(String str){
        int times = 0;
        while (str.contains("&") && str.contains(";")){
            str = StringEscapeUtils.unescapeHtml(str);
            times ++;
            if (times > 5){
                break;
            }
        }
        return str;
    }

}
